package com.example.http_image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

    /**
     * 返回url对应的图片内容
     * @param loadImage
     * @return
     */
    public static Bitmap loadImage(String sendUrl){

        HttpURLConnection conn = null;
        InputStream stream = null;

        try {
            URL url = new URL(sendUrl);
            /*
            使用httpurlconnection打开连接
             */
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            /*
            获取的数据转化为inputstream
             */
            stream = conn.getInputStream();

            /*
            加载outputstream对象来写入文件
             */
            FileOutputStream outputStream = null;
            File fileDownload = null;
            /*
            使用当前时间戳给图片命名
             */
            String fileName = String.valueOf(System.currentTimeMillis());
            /*
            载图片并存在sd卡内,判断SD卡是否是挂载的情况
             */
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                //parent目录
                File parent = Environment.getExternalStorageDirectory();
                //从父抽象路径名和子路径名字符串创建新的File实例
                fileDownload = new File(parent, fileName);
                outputStream = new FileOutputStream(fileDownload);
            }

            /*
            将stream内容写入到文件,创建一个缓冲区
             */
            byte[] bytes = new byte[2048];
            int lens;
            //判断sd卡有挂载的情况下才开始将输入流写入文件
            if (outputStream != null) {
                //还有内容没有读完，读的信息长度不为-1
                while ((lens = stream.read(bytes)) != -1) {
                    //从读到的第一个数开始写，直到读的所有数均被写进文件即可
                    outputStream.write(bytes, 0, lens);
                }
                return BitmapFactory.decodeFile(fileDownload.getAbsolutePath());
            }else {
                return null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if ( stream != null){
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn !=null){
                conn.disconnect();
            }
        }
        return null;
    }
}
